<?php

namespace App\Admin\Controllers;

use App\Models\Admin\AddressModel;
use App\Models\Admin\AdminModel;
use App\Models\Admin\OrderModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Http\Request;

class BoardController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '大数据看板';


    /**
     * 显示地图
     */
    public function map(Content $content){

        // $board = view('admin.board.map') -> render();
        $board = view('admin.board.map');
        return $content -> title('大数据看板') -> body($board);
    }


    /**
     * 获取省份数据
     */
    public function getProvince(Request $request,AdminModel $adminModel){
        $allCity = [];
        // 获取键
        $key = $request -> input('key');
        if($key == '中国' || empty($key)){
            $data = $this -> allProvinceData();
        }else{
            $data = $this -> allCityData($key);
        }

        return response() -> json([
            'error_code' => 0,
            'msg' => 'success',
            'max' => $data['max'],
            'data' => $data['data'],
            'a' => $allCity
        ]);
    }


    /**
     * 获取全市数据
     */
    protected function allCityData($provinceName){
        // 根据省获取全市
        $provinceId = AddressModel::where('name','=',$provinceName) -> value('id');
        $province = AddressModel::where('parent_id','=',$provinceId) -> pluck('name') -> toArray();

        $orderList = AdminModel::selectRaw(
                '
                        lj_order.id,
                        lj_order.admin_id,
                        count(*) as value,
                        sum(lj_order.sender_money) as all_sender_money,
                        sum(lj_order.goods_money) as all_goods_money,
                        count(distinct(lj_order.staff_id)) as all_staff_num,
                        count(distinct(lj_order.car_license)) as all_car_number,
                        lj_admin_users.province as name,
                        lj_admin_users.city
                    '
            )
            -> join('order','order.admin_id','admin_users.id')
            -> where('admin_users.province','=',$provinceName)
            -> groupBy('admin_users.city')
            -> get()
            -> toArray();
        //$province = [
        //    '北京', '天津', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '上海', '江苏',
        //    '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '重庆', '四川', '贵州',
        //    '云南', '西藏', '陕西', '甘肃', '青海', '宁夏', '新疆', '广东', '广西', '海南', '台湾',
        //];
        $data = [];
        if(count($orderList) == 0){
            $max = 0;
        }else{
            $max = max(array_column($orderList,'value'));
        }

        foreach ($orderList as $k => $v){
            if(in_array($v['city'],$province)){
                $temp = [
                    'name' => $v['city'],
                    'value' => $v['value'],
                    'all_sender_money' => $v['all_sender_money'],
                    'all_goods_money' => $v['all_goods_money'],
                    'all_staff_num' => $v['all_staff_num'],
                    'all_car_number' => $v['all_car_number'],
                ];
                $data[] = $temp;
                $k2 = array_search($v['city'],$province);
                if ($k2 !== false){
                    array_splice($province, $k2, 1);
                }
            }
        }

        foreach ($province as $k => $v){
            $temp = [
                'name' => $v,
                'value' => 0,
                'all_sender_money' => 0.00,
                'all_goods_money' => 0.00,
                'all_staff_num' => 0,
                'all_car_number' => 0,
            ];
            $data[] = $temp;
        }

        return [
            'max' => $max,
            'data' => $data
        ];
    }


    /**
     * 获取全省数据
     */
    protected function allProvinceData(){
        $orderList = AdminModel::selectRaw(
                '
                    lj_order.id,
                    lj_order.admin_id,
                    count(*) as value,
                    sum(lj_order.sender_money) as all_sender_money,
                    sum(lj_order.goods_money) as all_goods_money,
                    count(distinct(lj_order.staff_id)) as all_staff_num,
                    count(distinct(lj_order.car_license)) as all_car_number,
                    lj_admin_users.province as name,
                    lj_admin_users.city
                '
            )
            -> join('order','order.admin_id','admin_users.id')
            -> groupBy('admin_users.province')
            -> get()
            -> toArray();
        $province = [
            '北京', '天津', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '上海', '江苏',
            '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '重庆', '四川', '贵州',
            '云南', '西藏', '陕西', '甘肃', '青海', '宁夏', '新疆', '广东', '广西', '海南', '台湾',
        ];
        $data = [];

        $max = max(array_column($orderList,'value'));

        foreach ($orderList as $k => $v){
            if(in_array($v['name'],$province)){
                $temp = [
                    'name' => $v['name'],
                    'value' => $v['value'],
                    'all_sender_money' => $v['all_sender_money'],
                    'all_goods_money' => $v['all_goods_money'],
                    'all_staff_num' => $v['all_staff_num'],
                    'all_car_number' => $v['all_car_number'],
                ];
                $data[] = $temp;
                $k2 = array_search($v['name'],$province);
                if ($k2 !== false){
                    array_splice($province, $k2, 1);
                }
            }
        }

        foreach ($province as $k => $v){
            $temp = [
                'name' => $v,
                'value' => 0,
                'all_sender_money' => 0.00,
                'all_goods_money' => 0.00,
                'all_staff_num' => 0,
                'all_car_number' => 0,
            ];
            $data[] = $temp;
        }

        return [
            'max' => $max,
            'data' => $data
        ];
    }


    /**
     * 获取订单列表
     * @param int $scope 范围 1是全国 2是省 3是市
     * @param string $province 省份
     * @param string $city 市
     */
    public function orderList(Request $request,OrderModel $orderModel){
        \DB::connection() -> enableQueryLog();
        // 分组统计
        // 获取范围
        $scope = $request -> input('scope','');
        // 获取省
        $province = $request -> input('province','');
        // 获取市
        $city = $request -> input('city','');
        // 获取年
        $year = $request -> input('year');
        // 获取月
        $month = $request -> input('month');

        $query = $orderModel -> selectRaw(
            '
                lj_order.id,
                lj_order.admin_id,
                count(*) as order_num,
                sum(lj_order.sender_money) as all_sender_money,
                sum(lj_order.goods_money) as all_goods_money,
                count(distinct(lj_order.staff_id)) as all_staff_num,
                GROUP_CONCAT(distinct(lj_order.staff_id),",") as all_staff_ids,
                count(distinct(lj_order.car_license)) as all_car_number,
                lj_admin_users.province,
                lj_admin_users.city,
                lj_admin_users.username,
                lj_admin_users.company_name
            '
        );

        // 验证年是否为空
        if(!empty($year)){
            $query -> whereYear('order.created_at',$year);

            // 验证月份是否合法
            if(in_array($month,range(1,12))){
                $query -> whereMonth('order.created_at',$month);
            }
        }
        switch ($scope){
            case 2:
                // 查找所有的门店
                $adminIds = $this -> getProvinceAdminIds($province);
                $query -> whereIn('order.admin_id',$adminIds);
                break;

            case 3:
                $adminIds = $this -> getCityAdminIds($city);
                $query -> whereIn('order.admin_id',$adminIds);
                break;
        }

        $list = $query
            -> leftJoin('admin_users','admin_users.id','order.admin_id')
            -> groupBy('order.admin_id')
            -> paginate(15);

        $arr = $list -> toArray();
        foreach ($arr['data'] as $k => $v){
            $staffIds = array_unique(explode(',',$v['all_staff_ids']));
            $staff = \DB::table('staff') -> whereIn('id',$staffIds) -> pluck('staff_name') -> toArray();
            $v['all_staff_name'] = implode(',',$staff);
            $arr['data'][$k] = $v;
        }

        return response() -> json([
            'error_code' => 0,
            'msg' => 'success',
            'data' => $arr,
            'page' => htmlspecialchars_decode($list->links()),
            'param' => [
                'scope' => $scope,
                'province' => $province,
                'city' => $city
            ],
            // 'log' => \DB::getQueryLog()
        ]);

        return;

        // 获取范围
        $scope = $request -> input('scope','');
        // 获取省
        $province = $request -> input('province','');
        // 获取市
        $city = $request -> input('city','');

        $query = $orderModel -> where([]);
        switch ($scope){
            case 2:
                // 查找所有的门店
                $adminIds = $this -> getProvinceAdminIds($province);
                $query -> whereIn('admin_id',$adminIds);
                break;

            case 3:
                $adminIds = $this -> getCityAdminIds($city);
                $query -> whereIn('admin_id',$adminIds);
                break;
        }

        $list = $query -> orderBy('id','desc') -> paginate(1);

        return response() -> json([
            'error_code' => 0,
            'msg' => 'success',
            'data' => $list,
            'page' => htmlspecialchars_decode($list->links()),
            'param' => [
                'scope' => $scope,
                'province' => $province,
                'city' => $city
            ]
        ]);
    }


    /**
     * 获取
     * @param string $provinceName 省份名称
     */
    private function getProvinceAdminIds($provinceName){
        // 获取员id
        return $adminIds = AdminModel::where('province','=',$provinceName) -> pluck('id');
    }


    /**
     * 获取
     * $param string $cityName 市
     */
    private function getCityAdminIds($cityName){
        // 获取员id
        return $adminIds = AdminModel::where('city','=',$cityName) -> pluck('id');
    }


    /**
     * 添加
     */
    //public function addAddress(Request $request){
    //    $data = $request -> input('data');
    //    $data = explode('-',$data);
    //    $name = $request -> input('name');
    //    unset($data[0]);
    //
    //    // 查找
    //    $res = \DB::table('address') -> where('name','=',$name) -> first();
    //
    //    if($res){
    //        $a = \DB::table('address') -> where('parent_id','=',$res -> id) -> first();
    //        if(!$a){
    //            // 存在
    //            foreach ($data as $k => $v){
    //                \DB::table('address') -> insert([
    //                    'name' => $v,
    //                    'parent_id' => $res -> id,
    //                ]);
    //            }
    //        }
    //
    //    }
    //    return response() -> json([
    //        'error_code' => 0,
    //        'msg' => 'success',
    //        'data' => $data,
    //        'name' => $name,
    //        'res' => $res
    //    ]);
    //}


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new OrderModel);

        $grid->column('id', __('Id'));
        $grid->column('staff_id', __('Staff id'));
        $grid->column('order_number', __('Order number'));
        $grid->column('sender_province', __('Sender province'));
        $grid->column('sender_city', __('Sender city'));
        $grid->column('sender_district', __('Sender district'));
        $grid->column('sender_address', __('Sender address'));
        $grid->column('sender_name', __('Sender name'));
        $grid->column('sender_phone', __('Sender phone'));
        $grid->column('consignee_province', __('Consignee province'));
        $grid->column('consignee_city', __('Consignee city'));
        $grid->column('consignee_district', __('Consignee district'));
        $grid->column('consignee_address', __('Consignee address'));
        $grid->column('consignee_name', __('Consignee name'));
        $grid->column('consignee_phone', __('Consignee phone'));
        $grid->column('goods_number', __('Goods number'));
        $grid->column('order_money', __('Order money'));
        $grid->column('sender_money', __('Sender money'));
        $grid->column('goods_money', __('Goods money'));
        $grid->column('sender_pay_money', __('Sender pay money'));
        $grid->column('is_sender', __('Is sender'));
        $grid->column('is_collection', __('Is collection'));
        $grid->column('pay_status', __('Pay status'));
        $grid->column('order_status', __('Order status'));
        $grid->column('created_at', __('Created at'));
        $grid->column('updated_at', __('Updated at'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(OrderModel::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('staff_id', __('Staff id'));
        $show->field('order_number', __('Order number'));
        $show->field('sender_province', __('Sender province'));
        $show->field('sender_city', __('Sender city'));
        $show->field('sender_district', __('Sender district'));
        $show->field('sender_address', __('Sender address'));
        $show->field('sender_name', __('Sender name'));
        $show->field('sender_phone', __('Sender phone'));
        $show->field('consignee_province', __('Consignee province'));
        $show->field('consignee_city', __('Consignee city'));
        $show->field('consignee_district', __('Consignee district'));
        $show->field('consignee_address', __('Consignee address'));
        $show->field('consignee_name', __('Consignee name'));
        $show->field('consignee_phone', __('Consignee phone'));
        $show->field('goods_number', __('Goods number'));
        $show->field('order_money', __('Order money'));
        $show->field('sender_money', __('Sender money'));
        $show->field('goods_money', __('Goods money'));
        $show->field('sender_pay_money', __('Sender pay money'));
        $show->field('is_sender', __('Is sender'));
        $show->field('is_collection', __('Is collection'));
        $show->field('pay_status', __('Pay status'));
        $show->field('order_status', __('Order status'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new OrderModel);

        $form->number('staff_id', __('Staff id'));
        $form->text('order_number', __('Order number'));
        $form->text('sender_province', __('Sender province'));
        $form->text('sender_city', __('Sender city'));
        $form->text('sender_district', __('Sender district'));
        $form->text('sender_address', __('Sender address'));
        $form->text('sender_name', __('Sender name'));
        $form->number('sender_phone', __('Sender phone'));
        $form->text('consignee_province', __('Consignee province'));
        $form->text('consignee_city', __('Consignee city'));
        $form->text('consignee_district', __('Consignee district'));
        $form->text('consignee_address', __('Consignee address'));
        $form->text('consignee_name', __('Consignee name'));
        $form->number('consignee_phone', __('Consignee phone'));
        $form->number('goods_number', __('Goods number'))->default(1);
        $form->decimal('order_money', __('Order money'));
        $form->decimal('sender_money', __('Sender money'));
        $form->decimal('goods_money', __('Goods money'));
        $form->decimal('sender_pay_money', __('Sender pay money'));
        $form->number('is_sender', __('Is sender'));
        $form->number('is_collection', __('Is collection'))->default(2);
        $form->number('pay_status', __('Pay status'));
        $form->number('order_status', __('Order status'))->default(1);

        return $form;
    }
}
